var BASEURL = '';
var latitude = 0; // 纬度，浮点数，范围为90 ~ -90
var longitude = 0; // 经度，浮点数，范围为180 ~ -180。
var addr = '';
var station_id = '';
var stationList = [];
var rel_num = 0;

var ID_OPTIONS = [
    {
        value: '身份证',
        label: '身份证',
    },
    {
        value: '临时居民身份证',
        label: '临时居民身份证',
    },
    {
        value: '军官证',
        label: '军官证',
    },
    {
        value: '港澳居民往来内地通行证',
        label: '港澳居民往来内地通行证',
    },
    {
        value: '台湾居民往来内地通行证',
        label: '台湾居民往来内地通行证',
    },
    {
        value: '护照',
        label: '护照',
    },
    {
        value: '其他',
        label: '其他',
    },
];

function submit() {
    weui.form.validate('#form', function (error) {
        // 每次校验前先取消warn样式
        $('.weui-cell').removeClass('weui-cell_warn');
        if (!error) {
            var full_name = $('#full_name').val();
            var sex = $('input[name=sex]:checked').val();
            var id_type = $('#id_type').val();
            var id_card = $('#id_card').val().toUpperCase();
            var phone = $('#phone').val();
            var healthy = $('input[name=healthy]:checked').val();
            var temperature = $('input[name=temperature]:checked').val();
            var home_area = $('#home_area').val();
            var home_community = $('#home_community').val();
            var home_addr = $('#home_addr').val();
            var work_place = $('#work_place').val();
            var from_addr = $('#from_addr').val();
            var arrive_date = $('#arrive_date').val();
            var isolation = $('input[name=isolation]:checked').val();
            var contact_name = $('#contact_name').val();
            var contact_phone = $('#contact_phone').val();
            var contact_remark = $('#contact_remark').val();

            if (!isIdCard(id_card) && id_type === '身份证') {
                weui.form.showErrorTips({
                    ele: document.getElementById('id_card'),
                    msg: 'notMatch'
                });
                weui.alert('身份证不合法，请检查');
                return;
            } else {
                weui.form.hideErrorTips(document.getElementById("id_card"));
            }
            
            var relate_person = [];
            for (var i = 0; i < rel_num; i++) {
                if (!isIdCard($(`#rel_id_card_${i}`).val()) && id_type === '身份证') {
                    weui.form.showErrorTips({
                        ele: document.getElementById(`rel_id_card_${i}`),
                        msg: 'notMatch'
                    });
                    weui.alert('身份证不合法，请检查');
                    return;
                } else {
                    weui.form.hideErrorTips(document.getElementById(`rel_id_card_${i}`));
                }
                relate_person.push({
                    full_name: $(`#rel_name_${i}`).val(),
                    id_card: $(`#rel_id_card_${i}`).val().toUpperCase(),
                    temperature: $(`input[name=rel_temperature_${i}]:checked`).val(),
                });
            }

            var loading;
            loading = weui.loading('提交中...');

            var postData = {
                full_name: full_name.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5\ ]/g,''),
                sex: sex,
                id_type: id_type,
                id_card: id_card,
                phone: phone,
                healthy: healthy,
                temperature: temperature,
                home_area: home_area,
                home_community: home_community,
                home_addr: home_addr,
                work_place: work_place,
                from_addr: from_addr,
                arrive_date: arrive_date,
                isolation: isolation,
                contact_name: contact_name,
                contact_phone: contact_phone,
                contact_remark: contact_remark,
            };
            if (station_id) {
                postData.station_id = station_id;
            }
            if (relate_person.length > 0) {
                postData.relate_person = JSON.stringify(relate_person);
            }
            for(var key in postData) {
                postData[key] = filterXSS(postData[key]);
            }
            postData.addr = addr;
            postData.lat = latitude;
            postData.lon = longitude;
            postData.data_type = 1;

            console.log(postData);
            // saveValues(postData);

            $.ajax({
                url: `${BASEURL}/api/hubei/visit`,
                type: 'POST',
                data: postData,
                success: function(res) {
                    loading.hide();
                    if (res && res.success) {
                        saveValues(postData);
                        saveValues({warn: 0, lasttime: new Date().toLocaleString()});
                        // weui.toast('提交成功', 2000);
                        // window.location.reload();
                        window.location.assign(`success.html?redirect=${encodeURIComponent(window.location.href)}`);
                    } else {
                        if (res.errCode == 202) {
                            saveValues(postData);
                            saveValues({warn: 1, lasttime: new Date().toLocaleString()});
                            window.location.assign(`success.html?warn=1&redirect=${encodeURIComponent(window.location.href)}`);
                        } else if (res.errCode == 203) {
                            saveValues(postData);
                            saveValues({warn: 2, lasttime: new Date().toLocaleString()});
                            window.location.assign(`success.html?warn=2&redirect=${encodeURIComponent(window.location.href)}`);
                        } else if (res.errCode == 204) {
                            saveValues(postData);
                            saveValues({warn: 3, lasttime: new Date().toLocaleString()});
                            window.location.assign(`success.html?warn=3&redirect=${encodeURIComponent(window.location.href)}`);
                        } else {
                            weui.toast(res.errMsg || '请重试！', 2000);
                        }
                    }
                },
                error: function(err) {
                    console.log(err);
                    loading.hide();
                    weui.toast('系统错误！请刷新重试！');
                },
            })
        }
    }, {
        regexp: {
            PHONE: /^(86)?[1][3-9]\d{9}$|^(852)?([2|6|9])\d{7}$|^(853)?[6]([8|6])\d{5}$/,
            IDNUM: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            TEMPERATURE: /^[3,4]\d(\.\d{0,2})?$/,
        }
    });
}

function uploadImgs(data) {
}

function saveValues(values) {
    for(var key in values){
        localStorage.setItem(`2019ncov_${key}`, values[key]);
    }
}

function loadValue(key) {
    return localStorage.getItem(`2019ncov_${key}`);
}

function getPosition(lat, lon) {
    $.ajax({
        url: `https://api.map.baidu.com/reverse_geocoding/v3/?ak=uwwi4F76LXDyPNhdanYixzixEgPor0L6&output=json&coordtype=wgs84ll&location=${lat}%2C${lon}`,
        type: 'GET',
        dataType: 'jsonp',
        success: function(res){
            if (res.status == 0) {
                addr = res.result.formatted_address;
                if (!loadValue('home_area') && res.result.addressComponent) {
                    $("#home_area").val(`${res.result.addressComponent.province}-${res.result.addressComponent.city}-${res.result.addressComponent.district}`);
                }
            } else {
                addr = '';
            }
        },
        error: function (textStatus) { //请求失败后调用的函数
            addr = '';
        }
    });
}


function initValues() {
    $('#arrive_date').val(dateFormat(new Date(), 'yyyy-MM-dd'));

    var text_keys = ['full_name', 'id_type', 'id_card', 'phone', 'home_area', 'home_community', 'home_addr', 'work_place', 'contact_name', 'contact_phone', 'contact_remark', 'from_addr', 'arrive_date'];
    var radio_keys = ['sex', 'isolation'];

    for (var i = 0; i < text_keys.length; i++) {
        var savedValue = loadValue(text_keys[i]);
        if(savedValue) {
            $(`#${text_keys[i]}`).val(loadValue(text_keys[i]));
        }
    }
    for (var i = 0; i < radio_keys.length; i++) {
        var savedValue = loadValue(radio_keys[i]);
        if(savedValue) {
            $(`input[name=${radio_keys[i]}]:checked`).removeAttr('checked');
            $(`#${radio_keys[i]}${loadValue(radio_keys[i])}`).attr('checked', true);
        }
    }
}

function createAreaPicker(dom) {
    // 级联picker
    weui.picker(CITY_OPTIONS, {
        className: 'custom-classname',
        container: 'body',
        defaultValue: $(dom).val() ? $(dom).val().split("-") : loadValue('home_area') ? loadValue('home_area').split('-') : ['广东省', '深圳市', '南山区'],
        onChange: function (result) {
            $(dom).val(result[2] ? `${result[0].label}-${result[1].label}-${result[2].label}` : `${result[0].label}-${result[1].label}`);
        },
        onConfirm: function (result) {
            $(dom).val(result[2] ? `${result[0].label}-${result[1].label}-${result[2].label}` : `${result[0].label}-${result[1].label}`);
        },
        id: 'areaPicker'
    });
}

function getRelContent(index) {
    var content = `<div class="weui-panel" id="rel_pannel_${index}">
      <div class="weui-panel__bd">

        <div class="weui-cell">
          <div class="weui-cell__hd">
            <label class="weui-label"><span class="red-text">*</span>同住人${index + 1}</label>
          </div>
          <div class="weui-cell__bd">
            <input class="weui-input" required placeholder="请输入同住人姓名" id="rel_name_${index}">
          </div>
        </div>
        <div class="weui-cell">
          <div class="weui-cell__hd">
            <label class="weui-label"><span class="red-text">*</span>证件号码</label>
          </div>
          <div class="weui-cell__bd">
            <input class="weui-input" type="text" pattern="" placeholder="请输入同住人证件号码"
              emptyTips="请输入同住人身份证号码" notMatchTips="请输入正确的证件号码" id="rel_id_card_${index}">
          </div>
        </div>
        <div class="weui-cell">
          <div class="weui-cell__hd">
            <label class="weui-label"><span class="red-text">*</span>体温</label>
          </div>
          <div class="weui-cell__bd weui-cells_checkbox">
            <label class="weui-cell weui-cell_active weui-check__label" for="rel_temperature_${index}_0">
              <div class="weui-cell__hd">
                <input type="radio" class="weui-check" name="rel_temperature_${index}" id="rel_temperature_${index}_0" value="0" checked="checked"/>
                <span class="weui-icon-checked"></span>
              </div>
              <div class="weui-cell__bd">
                <p>37.3℃以下</p>
              </div>
            </label>
            <label class="weui-cell weui-cell_active weui-check__label" for="rel_temperature_${index}_1">
              <div class="weui-cell__hd">
                <input type="radio" class="weui-check" name="rel_temperature_${index}" id="rel_temperature_${index}_1" value="1"/>
                <span class="weui-icon-checked"></span>
              </div>
              <div class="weui-cell__bd">
                <p>37.3℃及以上</p>
              </div>
            </label>
          </div>
        </div>

      </div>
    </div>`;
    return content;
}

function loadJs(url, callback){
    var script = document.createElement('script');
    script.type = "text/javascript";
    if(typeof(callback) != "undefined") {
        if(script.readyState) {
            script.onreadystatechange = function() {
                if(script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    callback();
                }
            }
        } else {
            script.onload = function() {
                callback();
            }
        }
    }
    script.src = url;
    document.body.appendChild(script);
}

function getSzStation() {
    $.ajax({
        url: `${BASEURL}/api/police/query/stationList`,
        type: 'POST',
        data: {
            page: -1,
            city_id: 199,
        },
        success: function(res){
            if (res && res.success) {
                stationList = res.result.list;
                stationList = JSON.parse(JSON.stringify(stationList).replace(/name/g, 'label').replace(/area_id/g, 'value').replace(/station_id/g, 'value').replace(/station/g, 'children'));
                for (var i = 0; i < stationList.length; i++) {
                    if (stationList[i].children) {
                        for (var j = 0, temp = stationList[i].children; j < temp.length; j++) {
                            if (temp[j].value == station_id) {
                                szCallback();
                            }
                        }
                    }
                }
            } else {
                stationList = [];
            }
        },
        error: function (textStatus) { //请求失败后调用的函数
            console.log(textStatus);
            stationList = [];
        }
    });
}

function szCallback() {
    $('#sign').html('——深圳市公安局');
    $('.hide').removeClass('hide').addClass('sz_show');

    $('#home_community').on('click', function() {
        var home_area = $('#home_area').val();
        var arr = home_area ? home_area.split("-") : [];
        if(arr[1] !='深圳市'){
            // $('#topTips').fadeIn(200)
            // setTimeout(function(){
            //     $('#topTips').fadeOut(200)
            // },2000);
            $(this).focus();
            return;
        }
        if(arr.length === 3 && arr[1] === '深圳市') {
            $(this).blur();
            weui.picker(STREET_OPTIONS, {
                className: 'custom-classname',
                container: 'body',
                depth: 3,
                onChange: function (result) {
                    $('#home_community').val(`${result[0].label}-${result[1].label}-${result[2].label}`);
                },
                onConfirm: function (result) {
                    $('#home_community').val(`${result[0].label}-${result[1].label}-${result[2].label}`);
                },
                id: 'homeCommunity'
            });
        }
    });
}
function initAll(){
    station_id = getUrlParam('station_id');
    if (station_id) {
        getSzStation(station_id);
    } else {
        szCallback();
    }

    // 配置微信sdk
    // getWxConfig();

    if (getUrlParam('reregister') !== '1' && loadValue("id_card")) {
        window.location.replace(`success.html?redirect=${encodeURIComponent(window.location.href)}`);
    }

    $('#submit').on('click', submit);

    // wx.ready(function(){
    //     // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
    //     wx.checkJsApi({
    //       jsApiList: ['getLocation'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
    //       success: function(res) {
    //       // 以键值对的形式返回，可用的api值true，不可用为false
    //       // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
    //         if(res.checkResult.getLocation) {
    //             wx.getLocation({
    //               type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
    //               success: function (res) {
    //                 latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
    //                 longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
    //                 getPosition(res.latitude, res.longitude);
    //               }
    //             });
    //         } else {
                //判断是否支持 获取本地位置
                if (navigator.geolocation) {
                   var n = navigator.geolocation.getCurrentPosition(function(res){
                       console.log(res); // 需要的坐标地址就在res中
                       latitude = res.coords.latitude;
                       longitude = res.coords.longitude;
                       getPosition(res.coords.latitude, res.coords.longitude);
                   });
                } else {
                    alert('该浏览器不支持定位');
                }
    //         }
    //       }
    //     });
    // });

    $('#home_area').on('click', function() {
        $(this).blur();
        createAreaPicker("#home_area");
    });

    $('#id_type').on('click', function() {
        $(this).blur();
        weui.picker(ID_OPTIONS, {
            className: 'custom-classname',
            container: 'body',
            depth: 1,
            defaultValue: ['身份证'],
            onChange: function (result) {
                $('#id_type').val(`${result[0].label}`);
            },
            onConfirm: function (result) {
                $('#id_type').val(`${result[0].label}`);
            },
            id: 'idType'
        });
    });

    // 到达日期
    $('#arrive_date').on('click', function () {
        var $this = $(this);
        weui.datePicker({
            start: '2019-11-01',
            end: '2020-12-31',
            onChange: function (result) {
                $this.val(`${result[0].value}-${result[1].value < 10 ? '0' + result[1].value : result[1].value}-${result[2].value < 10 ? '0' + result[2].value : result[2].value}`);
            },
            onConfirm: function (result) {
                $this.val(`${result[0].value}-${result[1].value < 10 ? '0' + result[1].value : result[1].value}-${result[2].value < 10 ? '0' + result[2].value : result[2].value}`);
            },
            title: '到达本市日期',
        });
    });

    $("#del_rel_box").hide();

    $('#add_rel').on('click', function() {
        $('#rel_box').append(getRelContent(rel_num));
        rel_num ++;
        $("#del_rel_box").show();
    });

    $("#del_rel").on('click', function() {
        $('#rel_box').find(".weui-panel:last-child").remove();
        if (rel_num > 1) {
            rel_num --;
        } else {
            rel_num = 0;
            $("#del_rel_box").hide();
        }
    });

    $('input[name=is_leave]').on('change', function() {
        if($(this).val() === '0') {
            $("#arrive_date_box").hide();
            $("#from_addr_box").hide();
            $("#arrive_date").val("1970-01-01");
            $("#from_addr").val("").removeAttr("required");
        } else {
            $("#arrive_date_box").show();
            $("#from_addr_box").show();
            $("#arrive_date").val("");
            $("#from_addr").val("").attr("required", true);
        }
    });

    $('#from_addr').on('click', function() {
        $(this).blur();
        weui.picker(CITY_OPTIONS, {
            className: 'custom-classname',
            container: 'body',
            depth: 2,
            defaultValue: loadValue('from_addr') ? loadValue('from_addr').split('-') : ['湖北省', '武汉市'],
            onChange: function (result) {
                $('#from_addr').val(`${result[0].label}-${result[1].label}`);
            },
            onConfirm: function (result) {
                $('#from_addr').val(`${result[0].label}-${result[1].label}`);
            },
            id: 'cityPicker'
        });
    });
    
    // 地图选点
    // var stateCount = 0; // 用于解决非返回键关闭地图导致需要多次后退的问题
    // $("#home_addr").on('click', function() {
    //     $(this).blur();
    //     $("#mapPage").fadeIn(300);
    //     if (stateCount === 0) {
    //         window.history.pushState("","","#");
    //         stateCount++;
    //     }
    // });
    // window.addEventListener('message', function(event) {
    //     // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
    //     var loc = event.data;
    //     if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
    //         $("#mapPage").fadeOut(300);
    //         $("#home_addr").val(`${loc.poiaddress}-${loc.poiname}`);
    //     }
    // }, false);
    // window.addEventListener("popstate", function(e){
    //     $("#mapPage").fadeOut(100);
    //     stateCount--;
    // });

    // 初始化输入框默认值
    initValues();

}
$(function () {
    if(location.hash == '#visitorRegister'){
        initAll();
    }
    $(window).on('hashchange', function () {
        if( location.hash == '#visitorRegister'&&!station_id){
            initAll()
        }
     })
   
})
